package com.giftmail.client

import com.giftmail.handler.ClientHandler
import com.giftmail.server.NettyServer
import io.netty.bootstrap.Bootstrap
import io.netty.channel.ChannelInitializer
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.handler.codec.serialization.{ClassResolver, ClassResolvers, ObjectDecoder, ObjectEncoder}

class NettyClient {

  def connect(host:String,port:Int):Unit = {
    //创建客户端NIO线程池
    val eventGroup = new NioEventLoopGroup()
    //创建客户端辅助启动类
    val bootstrap = new Bootstrap
    try{
      //将NIO线程组传入到Boosstrap
      bootstrap.group(eventGroup)
        //创建NioSocketChannel
        .channel(classOf[NioSocketChannel])
        //绑定I/O事件处理类(childHandler处理器)
          .handler(new ChannelInitializer[SocketChannel] {
            override def initChannel(ch: SocketChannel):Unit ={
              ch.pipeline().addLast(

                //改造:第三步:RPC之间传递的case class数据,必须是序列化和反序列化的数据,故,如下处理
                  new ObjectEncoder,    //编码
                  new ObjectDecoder(ClassResolvers.cacheDisabled(getClass.getClassLoader)),   //解码

                  new ClientHandler
              )
            }
          })
      //发起异步连接操作
      val channelFuture = bootstrap.connect(host,port).sync()
      //等待服务关闭
      channelFuture.channel().closeFuture().sync()
    }finally {
      //优雅的退出,释放资源
      eventGroup.shutdownGracefully()
    }


  }
}

object NettyClient{
  def main(args: Array[String]): Unit = {

    val host = args(0)
    val port = args(1).toInt
    val client = new NettyClient
    client.connect(host, port)
  }
}
